﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using RuleCode.Table;
using System.Collections;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace map
{
    public class zfunction
    {
        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {

                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”，估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];     //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;     //代理中的内容 非IP，取IP 
                    }

                }

                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];



                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;

                return result;
            }
        }

        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

        public static string shortAddress(string address)
        {
            if (address.IndexOf(" ") > 0)
            {
                address = address.Substring(0, address.IndexOf(" "));
            }
            if (address.IndexOf("大学") > 0)
            {
                address = address.Substring(0, address.IndexOf("大学") + 2);
                return address;
            }
            if (address.IndexOf("区") > 0)
            {
                address = address.Substring(0, address.IndexOf("区") + 1);
                return address;
            }
            if (address.IndexOf("县") > 0)
            {
                address = address.Substring(0, address.IndexOf("县") + 1);
                return address;
            }
            if (address.IndexOf("市") > 0)
            {
                address = address.Substring(0, address.IndexOf("市") + 1);
                return address;
            }
            if (address.IndexOf("省") > 0)
            {
                address = address.Substring(0, address.IndexOf("省") + 1);
                return address;
            }
            if (address.IndexOf("自治区") > 0)
            {
                address = address.Substring(0, address.IndexOf("自治区") + 3);
                return address;
            }
            return address;

        }

        static public Int32 str2int(string str)
        {
            try
            {
                return Convert.ToInt32(str);
            }
            catch (Exception)
            {

                return 0;
            }
            return 0;
        }
        static public double str2double(string str)
        {
            try
            {
                return Convert.ToDouble(str);
            }
            catch (Exception)
            {

                return 0;
            }
            return 0;
        }
        static public Int64 str2int64(string str)
        {
            try
            {
                return Convert.ToInt64(str);
            }
            catch (Exception)
            {

                return 0;
            }
            return 0;
        }
        /// <summary>
        /// 替换 KeyWord中的非法字符
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        public static string ReplaceKeyWord(string keyWord)
        {
            if (keyWord == null)
            {
                return "";
            }
            keyWord = keyWord.Replace("'", "");
            string result = "%" + keyWord + "%";
            keyWord = "%" + keyWord + "%";
            foreach (char invalidLetter in InvalidKeyLetters)
            {
                result = keyWord.Replace(invalidLetter, '%');
            }
            bool existDouble = result.Contains("%%");
            while (existDouble)
            {
                result = result.Replace("%%", "%");
                existDouble = result.Contains("%%");
            }
            return result;
        }
        /// <summary>
        /// 获取 KeyWord 搜索框里面的 将要替换的字符
        /// </summary>
        public static char[] InvalidKeyLetters
        {
            get
            {
                char[] invalidKeyLetters = new char[] { ',', '.', ' ', '?', '&', '+', '>', '<' };
                return invalidKeyLetters;
            }
        }

        public static Int64 ip2int(string ip)
        {
            try
            {
                Int64 re = 0;
                string tmp;
                tmp = ip.Substring(0, ip.IndexOf("."));
                re += zfunction.str2int64(tmp) * 16777216;
                tmp = ip.Substring(ip.IndexOf(".") + 1);

                tmp = ip.Substring(0, ip.IndexOf("."));
                re += zfunction.str2int64(tmp) * 65536;
                tmp = ip.Substring(ip.IndexOf(".") + 1);

                tmp = ip.Substring(0, ip.IndexOf("."));
                re += zfunction.str2int64(tmp) * 256;
                tmp = ip.Substring(ip.IndexOf(".") + 1);

                tmp = ip.Substring(0, ip.IndexOf("."));
                re += zfunction.str2int64(tmp);

                return re;
            }
            catch (Exception)
            {

                return 0;
            }
            return 0;
        }


        static public string Province
        {
            get
            {
                string _province = string.Empty;
                if (HttpContext.Current.Request.Cookies["f980"] != null && HttpContext.Current.Request.Cookies["f980"]["area"] != null)
                    _province = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies["f980"]["area"]);
                else
                {
                    if (AliApi.appUserId != string.Empty)
                    {
                        cbuser user = cbuser.Find("cbuserid='" + AliApi.appUserId + "'");
                        if (user.Count > 0)
                            _province = user.省编码.Value;
                    }
                    if (_province == string.Empty)
                    {
                        string myip = zfunction.IPAddress;
                        myip = zfunction.ip2int(myip).ToString();
                        string sql = " select taobaostate from taobaoip2 where taobaoipintfrom <=  "
                                        + myip + " and taobaoipintto >= " + myip;
                        DataSet dSet = RuleCode.Common.SqlHelper.Instance.ExecuteQuery(sql);
                        if (dSet.Tables.Count > 0 && dSet.Tables[0].Rows.Count > 0)
                            _province = dSet.Tables[0].Rows[0][0].ToString();
                    }                            
                    RuleCode.Table.cbuser.setprovince(_province);
                }
                if (_province.Trim() == string.Empty || (!AllProvinceList.Contains(_province)))
                {
                    _province = "北京";
                    RuleCode.Table.cbuser.setprovince(_province);
                }
                return _province;

            }
            set
            {
                string _province = value;
                if (_province.Trim() == string.Empty || (!AllProvinceList.Contains(_province)))
                {
                    _province = "北京";
                }
                RuleCode.Table.cbuser.setprovince(_province);

            }
        }

        static public Hashtable recidht;
        static public int recidhtint = 0;
        static public string getrecid(string userid)
        {
            recidhtint++;
            if (recidht == null || recidhtint == 100)
            {
                recidhtint -= 100;
                cbuser u = cbuser.Find("1=1");
                recidht = new Hashtable(u.Count);
                foreach (DataRow item in u.MyTable.Rows)
                {
                    recidht.Add(item["cbuserid"].ToString(), item["RECID"].ToString());
                }
            }
            if (recidht[userid] == null)
            {
                return "";
            }
            else
            {
                return recidht[userid].ToString();
            }
        }

        private static List<string> _allProvinceList;
        public static List<string> AllProvinceList
        {
            get
            {
                if (_allProvinceList == null)
                {
                    _allProvinceList = new List<string>();
                    省 state = 省.Find("1=1");
                    if (state.Count > 0)
                    {
                        for (int i = 0; i < state.Count; i++)
                        {                               
                            _allProvinceList.Add(state.省编码 .Value );
                            state.Next();
                        }
                    }
                }
                return _allProvinceList;
            }
        }


        /// <summary>
        /// 获取聊天室状态
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static bool getuserstatus(string userId)
        {
            cbuser user = cbuser.Find("cbuserid='"+userId +"'");
            if (user.Count > 0 && user.chatIsOnLine .Value == RuleCode.Enum.BooleanEnum .Yes )
                return true;
            return false;
        }


        /// <summary>
        /// 判断是否为管理员账户
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static bool IsAdministrator(string userid)
        {
            return (userid == "maxfara@163.com");
        }

    }
}

namespace chatblog
{
    public class zfunction
    {

        static public Hashtable ht;
        static public int htint = 0;
        static public string getnick(string userid)
        {
            htint++;
            if (ht == null || htint == 100)
            {
                htint -= 100;
                cbuser u = cbuser.Find("1=1");
                ht = new Hashtable(u.Count);
                foreach (DataRow item in u.MyTable.Rows)
                {
                    ht.Add(item["cbuserid"].ToString(), item["cbusernickname"].ToString());
                }
            }
            if (ht[userid] == null)
            {
                return "";
            }
            else
            {
                return ht[userid].ToString();
            }
        }


        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”，估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];     //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;     //代理中的内容 非IP，取IP 
                    }

                }

                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];



                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;

                return result;
            }
        }

        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

        static public Int32 str2int(string str)
        {
            try
            {
                return Convert.ToInt32(str);
            }
            catch (Exception)
            {

                return 0;
            }
            return 0;
        }
        /// <summary>
        /// 替换 KeyWord中的非法字符
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        public static string ReplaceKeyWord(string keyWord)
        {
            keyWord = keyWord.Replace("'", "");
            string result = "%" + keyWord + "%";
            keyWord = "%" + keyWord + "%";
            foreach (char invalidLetter in InvalidKeyLetters)
            {
                result = keyWord.Replace(invalidLetter, '%');
            }
            bool existDouble = result.Contains("%%");
            while (existDouble)
            {
                result = result.Replace("%%", "%");
                existDouble = result.Contains("%%");
            }
            return result;
        }
        /// <summary>
        /// 获取 KeyWord 搜索框里面的 将要替换的字符
        /// </summary>
        public static char[] InvalidKeyLetters
        {
            get
            {
                char[] invalidKeyLetters = new char[] { ',', '.', ' ', '?', '&', '+', '>', '<' };
                return invalidKeyLetters;
            }
        }



        public static string getchatroomlink(string type, string recid)
        {
            Int32 i = CommonChatRoomCache.GetRoomUserCount(recid);
            string ret = "";
            System.Web.UI.Control c = new System.Web.UI.Control();
            if (i > 0)
            {
                ret = "<a href=\"" + c.ResolveUrl("~/CommonChat/CommonChatRoom.aspx?ID=") + recid.ToString() + "&Type=" + type +
                    "\"  target=\"_blank\" style=\"text-decoration:none;\"> <img src=\"../img/announcement.gif\"  style=\"border:0;\"/>(" + i.ToString() + ")</a>";
            }
            else
            {
                ret = "<a href=\"" + c.ResolveUrl("~/CommonChat/CommonChatRoom.aspx?ID=") + recid.ToString() + "&Type=" + type +
                    "\"  target=\"_blank\" style=\"text-decoration:none;\"> <img src=\"../img/announcement2.gif\"  style=\"border:0;\"/>(0)</a>";
            }
            return ret;
        }

        public static string getfromchatroomid(string type, string recid)
        {
            string ret = "";
            if (type == "1")
            {
                cblist l = cblist.Find(" RECID =" + recid);
                ret = l.cbtitle.ToString();
            }
            if (type == "2")
            {
                cbcata l = cbcata.Find(" RECID =" + recid);
                ret = l.cbname.ToString();
            }
            return ret;
        }


        
    }
}
